package liquidfs.ui.web;

import java.io.*;
import java.util.logging.*;

import liquidfs.*;

import com.sun.net.httpserver.*;

class BufferedHandler implements HttpHandler {

   private Application app;
   private byte[] cache;
   
   private static Logger log = Logger.getLogger("liquidfs.ui.web");
   
   public BufferedHandler (Application app, InputStream stream) throws IOException {
      this.app = app;
      
      // Create an expandable buffer to hold the contents of the stream. Assume about a 20KB file.
      ByteArrayOutputStream buffer = new ByteArrayOutputStream(20 * 1024);
      cache = new byte[4 * 1024];
      int read;
      
      do {
         read = stream.read(cache);
         
         if (read > 0)
            buffer.write(cache, 0, read);
      }
      while (read != -1);
      
      // Save the buffer in our local cache, so we can serve the web page very quickly
      cache = buffer.toByteArray();
      
      // We wasted a lot of memory doing that. Clean up soon.
      buffer = null;
      System.gc();
      
   }
   
   @Override
   public void handle(HttpExchange http) throws IOException {
      
      log.info("Serving " + http.getHttpContext().getPath());
      
      // Send the cached file
      http.sendResponseHeaders(200, cache.length);
      http.getResponseBody().write(cache);
      http.close();
      
   }
   
}